package kdt

import (
	"encoding/json"
	"fmt"
	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
	"io/ioutil"
	"net/http"
)

func UserRegister(w http.ResponseWriter, r *http.Request) {
	crossDomain(w)
	b, _ := ioutil.ReadAll(r.Body)
	u := User{}
	e := json.Unmarshal(b, &u)
	if e != nil {
		ReturnInfo(w, "ERR", e.Error())
		return
	}
	if _, e = getUserByPhone(u.Phone); e == nil {
		ReturnInfo(w, "ERR", "account exists")
		return
	}
	u.Uid = NewToken()
	u.Sid = u.Uid
	e = addUser(u)
	if e != nil {
		ReturnInfo(w, "ERR", e.Error())
		return
	}
	ReturnInfo(w, "OK", u.Sid)
}
func UserLogin(w http.ResponseWriter, r *http.Request) {
	crossDomain(w)
	b, _ := ioutil.ReadAll(r.Body)
	u := User{}
	e := json.Unmarshal(b, &u)
	if e != nil {
		ReturnInfo(w, "ERR", e.Error())
		return
	}
	gu, e := getUserByPhone(u.Phone)
	if e != nil {
		ReturnInfo(w, "ERR", e.Error())
		return
	}
	if gu.Password != u.Password {
		ReturnInfo(w, "ERR", "password incorrect")
		return
	}
	ReturnInfo(w, "OK", gu.Sid)
}
func getUserBySid(sid string) (User, error) {
	u := User{}
	s, e := mgo.Dial(MongoDBServer)
	if e != nil {
		fmt.Println(e)
		return u, e
	}
	defer s.Close()
	e = s.DB("kdt").C("users").Find(bson.M{"sid": sid}).One(&u)
	if e != nil {
		fmt.Println(e)
		return u, e
	}
	return u, nil
}
func getUserByPhone(phone string) (User, error) {
	u := User{}
	s, e := mgo.Dial(MongoDBServer)
	if e != nil {
		fmt.Println(e)
		return u, e
	}
	defer s.Close()
	e = s.DB("kdt").C("users").Find(bson.M{"phone": phone}).One(&u)
	if e != nil {
		return u, e
	}
	return u, nil
}
func addUser(u User) error {
	s, e := mgo.Dial(MongoDBServer)
	if e != nil {
		fmt.Println(e)
		return e
	}
	defer s.Close()
	e = s.DB("kdt").C("users").Insert(u)
	if e != nil {
		return e
	}
	return nil
}
